package com.ust.app.movie.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ust.app.movie.entity.Genre;
import com.ust.app.movie.entity.Movie;
import com.ust.app.movie.service.MovieService;

public class MovieServiceImpl implements MovieService {

	private SessionFactory sessionFactory;
	
	public MovieServiceImpl(){
		
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getCurrentSession(){
		return this.sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public List<Movie> getAllMovies() throws Exception{
		getCurrentSession().beginTransaction();
		Query query = getCurrentSession().createQuery("from Movie m order by m.genre.name");
		return query.list();
	}

	public Movie getMovie(int id) throws Exception{
		getCurrentSession().beginTransaction();
		
		Query query = getCurrentSession().createQuery("from Movie m where m.id = :id");
		query.setParameter("id", id);
		
		return (Movie) query.uniqueResult();
	}

	public void addMovie(Movie movie) {		
		getCurrentSession().beginTransaction();
		getCurrentSession().save(movie);
		getCurrentSession().getTransaction().commit();		
	}

	public void updateMovie(Movie movie) throws Exception {
		getCurrentSession().beginTransaction();
		getCurrentSession().merge(movie);		
		getCurrentSession().getTransaction().commit();
	}

	public void deleteMovie(Movie movie) {	
		getCurrentSession().beginTransaction();
		getCurrentSession().delete(movie);
		getCurrentSession().getTransaction().commit();
	}

	@SuppressWarnings("unchecked")
	public List<Genre> getAllGenres() {
		getCurrentSession().beginTransaction();
		Query query = getCurrentSession().createQuery("from Genre g order by g.name");
		return query.list();
	}
	
	public void deleteMovieById(int id) throws Exception{
		getCurrentSession().beginTransaction();
		Query query = getCurrentSession().createQuery("delete from Movie m where m.id = :id");
		query.setParameter("id", id);
		query.executeUpdate();
		getCurrentSession().getTransaction().commit();
	}

	public Genre getGenreById(int id) throws Exception {
		getCurrentSession().beginTransaction();
		
		Query query = getCurrentSession().createQuery("from Genre g where g.id = :id");
		query.setParameter("id", id);
		
		return (Genre) query.uniqueResult();
	}

}
